﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ViewRidgeAssistant
{
    public partial class form_transaction : Form
    {

        private main _parent_main;
        private work_form _parent_work;
        private data_source _data_module;

        private string _action;
        public class_work _work;
        public class_customer _customer;
        private string _state;
        public class_transaction _transaction;

        private string _trans_id;

        private class_customer[] _customers_list;
        private class_work[] _works_list;

        public form_transaction()
        {
            InitializeComponent();
        }

        //Конструктор вызова редактирования транзакции из главного окна приложения
        public form_transaction(data_source data_module, int trans_id)
        {
            InitializeComponent();
            this._trans_id = trans_id.ToString();
            this._data_module = data_module;
            this._action = "edit";
            this.edit_transaction();
        }

        //Конструктор оформления покупки/продажи картины
        public form_transaction(data_source data_module, class_work work, string action)
        {
            InitializeComponent();
            this._data_module = data_module;
            this._work = work;
            this.set_action(action);
            switch (this._action)
            {
                case "sale":
                    this.create_sale();
                    break;
                case "purchase":
                    this.create_purchase();
                    break;
            }
        }

        //Редактирование существующей транзакции
        private void edit_transaction()
        {
            this.Text = "Редактирование транзации";
            this.get_works_list();
            this.get_customers_list();
            this.fill_customers_list();
            this.fill_works_list();
            fill_trans_data();
            this.set_action("edit");
        }

        //Установить текущее действие
        private void set_action(string action)
        {
            this._action = action;
            switch (this._action)
            {
                case "sale":
                    this.t_customer.Enabled = false;
                    this.t_sales_price.Enabled = false;
                    this.dt_pur_date.Enabled = false;
                    this.b_delete.Enabled = false;
                break;
                case "purchase":
                this.b_delete.Enabled = false;
                break;
            }
        }

        //оформить продажу картины
        private void create_purchase()
        {
            this.get_works_list();
            this.get_customers_list();

            this.Text = "Оформление продажи картины";
            if (this._work != null)
            {
                this._trans_id = this.check_work_state();
                if (this._trans_id != "NOT_IN_GALLERY")
                {
                    this._transaction = this._data_module.get_transaction(Convert.ToInt32(this._trans_id));

                    this.dt_acq_date.Text = this._transaction.data_acq;
                    this.t_acq_price.Text = this._transaction.acq_price;
                    this.t_ask_price.Text = this._transaction.ask_price;
                    if (this._transaction.pur_date == "")
                    {
                        this.cb_not_pd.Checked = false;
                        this.cb_not_pd_changed(this, null);
                    }
                    else
                    {
                        this.dt_pur_date.Text = this._transaction.pur_date;
                    }
                    this.t_sales_price.Text = this._transaction.sales_price;

                    this.t_work.Text = this._work.title;
                    this.t_copy.Text = this._work.copy;

                    this.t_work.Enabled = false;
                    this.t_copy.Enabled = false;

                    this.get_customers_list();
                    this.fill_customers_list();

                    return;
                }
            }
            else
            {
                this._transaction = new class_transaction();
            }
            this.fill_customers_list();
            this.fill_works_list();
        }

        //загрузка списка клиентов
        private void get_customers_list()
        {
            this._customers_list = this._data_module.get_customers_list();
        }

        //заполнение списка клиентов
        private void fill_customers_list()
        {
            if (this._customers_list != null)
            {
                this.t_customer.Items.Clear();
                for (int i = 1; i < this._customers_list.Count(); i++)
                {
                    if (this._customers_list[i] != null)
                    {
                        this.t_customer.Items.Add(this._customers_list[i].name.Trim() + " (" + this._customers_list[i].email.Trim() + ")");
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        //загрузка списка названий работ
        private void get_works_list()
        {
            this._works_list = this._data_module.get_works_list();
        }

        //заполнение списка названий работ
        private void fill_works_list()
        {
            if (this._works_list != null)
            {
                this.t_work.Items.Clear();
                for (int i = 1; i < this._works_list.Count(); i++)
                {
                    if (this._works_list[i] == null)
                        break;
                    this.t_work.Items.Add(this._works_list[i].title);
                }
            }
        }

        //заполнение списка номеров копий работ
        private bool do_fill_copies_list;
        private void fill_copies_list()
        {
            if (do_fill_copies_list) return;
            do_fill_copies_list = true;
            try
            {
                this.t_copy.Items.Clear();
                for (int i = 1; i < this._works_list.Count(); i++)
                    if ((this._works_list[i] != null) && (this.t_work.Text == this._works_list[i].title))
                    {
                        this.t_copy.Items.Add(this._works_list[i].copy);
                        this.t_copy.Text = this._works_list[i].copy;
                    }
            }
            finally
            {
                do_fill_copies_list = false;
            }
            //this.t_copy.TextChanged += this.t_work_TextChanged;
        }

        //проверка наличия работы в галерее
        private String check_work_state()
        {
            return this._data_module.get_work_state(Convert.ToInt32(this._work.work_id));
        }

        //заполнить форму транзакции по IDнтификатору
        private void fill_trans_data()
        {
            this._transaction = this._data_module.get_transaction(Convert.ToInt32(this._trans_id));
            if (this._transaction.result == "OK")
            {
                this.t_acq_price.Text = this._transaction.acq_price;
                this.t_ask_price.Text = this._transaction.ask_price;
                this.t_sales_price.Text = this._transaction.sales_price;
                this.dt_acq_date.Text = this._transaction.data_acq;
                if (this._transaction.pur_date == "")
                {
                    this.cb_not_pd.Checked = false;
                    this.cb_not_pd_changed(this, null);
                }
                else
                {
                    this.dt_pur_date.Text = this._transaction.pur_date;
                }

                if (this._transaction.customer_name == "")
                {
                    this.t_customer.Text = "";
                }
                else
                {
                    this.t_customer.Text = this._transaction.customer_name + " (" + this._transaction.customer_email + ")";
                }
                this.t_work.Text = this._transaction.work_title;
                this.t_copy.Text = this._transaction.work_copy;
            }
            else
            {
                MessageBox.Show("Ошибка при загрузке данных транзакции");
                this.Close();
            }
        }

        //оформление покупку картины галереей
        private void create_sale()
        {
            this.Text = "Оформление покупки картины галереей";
            this.b_delete.Enabled = false;
            this.get_customers_list();
            this.get_works_list();
            this.fill_customers_list();
            this.fill_works_list();
            this._transaction = new class_transaction();
        }

        //проверка корректности указанных в форме транзакции данных 
        private bool check_trans_mod()
        {
            string cust_name = "";
            string cust_email = "";

            this._transaction.work_id = this._data_module.get_work_id_by_info(this.t_work.Text, this.t_copy.Text);
            if (this._transaction.work_id == null)
            {
                MessageBox.Show("Неправильно указана картина!");
                return false;
            }

            string cust_info = this.t_customer.Text.Trim();
            if (cust_info != "")
            {
                cust_name = this.t_customer.Text.Substring(0, this.t_customer.Text.IndexOf('(') - 1).Trim();
                cust_email = this.t_customer.Text.Substring(this.t_customer.Text.IndexOf('(') + 1, this.t_customer.Text.IndexOf(')') - this.t_customer.Text.IndexOf('(') - 1).Trim();
                this._transaction.customer_id = this._data_module.get_customer_id_by_info(cust_name, cust_email);
                if (this._transaction.customer_id == null)
                {
                    MessageBox.Show("Неправильно указан клиент!");
                    return false;
                }
            }
            else
            {
                cust_name = "";
                cust_email = "";
            }

            this._transaction.work_title = this.t_work.Text;
            this._transaction.work_copy = this.t_copy.Text;
            this._transaction.customer_name = cust_name;
            this._transaction.customer_email = cust_email;

            return true;
        }

        //Нажатие кнопки сохранения
        private void button1_Click(object sender, EventArgs e)
        {
            string result = "";              //Результат попытки сохранения/добавления транзакции
            if (!(this.check_trans_mod()))
            {
                return;
            }

            string p_date;
            if (this.cb_not_pd.Checked)
            {
                p_date = this.dt_pur_date.Value.ToString("MM.dd.yyyy");
            }
            else
            {
                p_date = "";
            }

            switch (this._action)
            {
                //редактирование сделки
                case "edit":
                case "purchase":
                    this.l_status.Text = "Обновление данных...";
                    result = this._data_module.upd_transaction(Convert.ToInt32(this._transaction.transaction_id),
                                                                Convert.ToInt32(this._transaction.work_id),
                                                                this._transaction.customer_id,
                                                                this.dt_acq_date.Value.Date.ToString("MM.dd.yyyy"),
                                                                this.t_acq_price.Text, p_date,
                                                                this.t_sales_price.Text, this.t_ask_price.Text);
                    break;

                //Покупка картины
                case "sale":
                    this.l_status.Text = "Сохранение покупки картины";
                    if (this._data_module.get_work_state(Convert.ToInt32(this._transaction.work_id)) != "NOT_IN_GALLERY")
                    {
                        MessageBox.Show("Эта картина уже куплена галереей!");
                        return;
                    }
                    MessageBox.Show("fjf");
                    result = this._data_module.add_default_transaction(Convert.ToInt32(this._transaction.work_id),
                                                                this.dt_acq_date.Value.Date.ToString("MM.dd.yyyy"),
                                                                this.t_acq_price.Text, this.t_ask_price.Text);
                    break;
            }

            if (result == "OK")
            {
                this.Close();
            }
            else
            {
                this.l_status.Text = "Ошибка";
                MessageBox.Show(result);
            }
        }

        //Удаление транзакции
        private void b_delete_Click(object sender, EventArgs e)
        {
            string result = this._data_module.del_record_by_id("TRANS", Convert.ToInt32(this._trans_id));
            if (result == "OK")
            {
                this.Close();
                this.Dispose();
            }
            else
            {
                MessageBox.Show(result);
            }
        }

        //Проверка доступности выбранной картины (в случае покупки - куплена ли, в случае продажи - есть ли в галерее)
        private void t_work_TextChanged(object sender, EventArgs e)
        {
            //this.t_work.TextChanged -= this.t_work_TextChanged;
            this.t_copy.TextChanged -= this.check_work_available;
            this.fill_copies_list();
            //this.t_work.TextChanged -= this.t_work_TextChanged;
            this.t_copy.TextChanged += this.check_work_available;
            this.check_work_available(this, null);
        }

        private void check_work_available(object sender, EventArgs e)
        {
            if (this._action == "purchase")
            {
                String work_id = this._data_module.get_work_id_by_info(this.t_work.Text, this.t_copy.Text);
                if (work_id != null)
                {
                    String trans_id = this._data_module.get_work_state(Convert.ToInt32(work_id));
                    if (trans_id != "NOT_IN_GALLERY")
                    {
                        this._transaction = this._data_module.get_transaction(Convert.ToInt32(trans_id));
                        this.t_ask_price.Text = this._transaction.ask_price;
                        this.t_acq_price.Text = this._transaction.acq_price;
                        this.dt_acq_date.Text = this._transaction.data_acq;
                        if (this._transaction.pur_date == "")
                        {
                            this.cb_not_pd.Checked = false;
                            this.cb_not_pd_changed(this, null);
                        }
                        else
                        {
                            this.dt_pur_date.Text = this._transaction.pur_date;
                        }
                        this.b_save.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Картины нет в галерее");
                        this.b_save.Enabled = false;
                    }
                }
                else
                {
                    MessageBox.Show("Неверно указана картина");
                    this.b_save.Enabled = false;
                }
            }

            if (this._action == "sale")
            {
                String work_id = this._data_module.get_work_id_by_info(this.t_work.Text, this.t_copy.Text);
                if (work_id != null)
                {
                    String trans_id = this._data_module.get_work_state(Convert.ToInt32(work_id));
                    if (trans_id == "NOT_IN_GALLERY")
                    {
                        this.b_save.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Картина уже куплена!");
                        this.b_save.Enabled = false;
                    }
                }
                else
                {
                    MessageBox.Show("Неверно указана картина");
                    this.b_save.Enabled = false;
                }
            }
        }

        private void cb_not_pd_changed(object sender, EventArgs e)
        {
            this.dt_pur_date.Enabled = this.cb_not_pd.Checked;
        }

    }
}